package com.wbs.shop.nuby.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.RelativeLayout;

import com.wbs.shop.nuby.R;


/**
 * Created by zhoucl on 2016/6/27.
 */
public class SquareRelativeLayout extends RelativeLayout {
    public static final float DEFAUTL_SCALE = 1;//默认比例,高等于宽
    private float heightScaleWidth = DEFAUTL_SCALE;
    public SquareRelativeLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context,attrs);
    }

    public SquareRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context,attrs);
    }

    public SquareRelativeLayout(Context context) {
        super(context);
        init(context,null);
    }

    private void init(Context context, AttributeSet attrs){
        TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SquareRelativeLayout,0, 0);
        heightScaleWidth = typedArray.getFloat(R.styleable.SquareRelativeLayout_heightScaleWidth,DEFAUTL_SCALE);
        typedArray.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec));

        int childWidthSize = getMeasuredWidth();

        if (heightScaleWidth != DEFAUTL_SCALE){
            widthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY);
            // 有一点精度丢失问题,很小忽略不计
            heightMeasureSpec = MeasureSpec.makeMeasureSpec((int) (childWidthSize * heightScaleWidth), MeasureSpec.EXACTLY);
        }else {
            // 高度和宽度一样
            heightMeasureSpec = widthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}
